package com.uusoft.core.utils.db;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.uusoft.core.exception.CommException;
import com.uusoft.core.utils.Assert;
import com.uusoft.core.utils.StringUtils;
import com.uusoft.core.utils.security.EncryptUtils;

/**
 * JNDI数据源提供者
 * @author shisheng.lian
 *
 */
public class JndiDataSourceAdapter extends AbsDataSourceAdapter implements DataSourceAdapter {
	
	private static final String JNDI_NAME = "jndiName";
	private static final String INITIAL_CONTEXT_FACTORY = Context.INITIAL_CONTEXT_FACTORY;
	private static final String PROVIDER_URL = Context.PROVIDER_URL;
	private static final String SECURITY_PRINCIPAL = Context.SECURITY_PRINCIPAL;
	private static final String SECURITY_CREDENTIALS = Context.SECURITY_CREDENTIALS;

	public void init() {
		Properties jndiPropertiesGroup = getDSPropertiesGroup();
		String jndiName = jndiPropertiesGroup.getProperty(JNDI_NAME);
		Assert.nullString(jndiName, "从配置文件中获取JNDI名称为空!");
		
		String principal = jndiPropertiesGroup.getProperty(SECURITY_PRINCIPAL);
		String credentials = jndiPropertiesGroup.getProperty(SECURITY_CREDENTIALS);
		principal = EncryptUtils.decryptSensitivity(principal);
		credentials = EncryptUtils.decryptSensitivity(credentials);
		
		String initialFactory = jndiPropertiesGroup.getProperty(INITIAL_CONTEXT_FACTORY);
		String providerUrl = jndiPropertiesGroup.getProperty(PROVIDER_URL);
		
		Properties props = new Properties();
		if (!StringUtils.isNull(initialFactory)) {
			props.setProperty(INITIAL_CONTEXT_FACTORY, initialFactory);
		}
		
		if (!StringUtils.isNull(providerUrl)) {
			props.setProperty(PROVIDER_URL, providerUrl);
		}

		if (!StringUtils.isNull(principal)) {
			props.setProperty(SECURITY_PRINCIPAL, principal);
		}

		if (!StringUtils.isNull(credentials)) {
			props.setProperty(SECURITY_CREDENTIALS, credentials);
		}

		try {
			InitialContext ctx = new InitialContext(props);
			setDs((DataSource)ctx.lookup(jndiName));
		} catch (NamingException e) {
			throw new CommException("建立JNDI数据源连接失败", e);
		}
	}

}
